/**
 * 反转 style标签 中 keyframe动画 -- reverse  css Animation
 * @param {Element} styleEl -- 自定義 style
 */
function rebackAnimation(styleEl) {
  //匹配 % | from to 字段名 和 `{[^}]*?}` 最小字段數據
  //groups 字段 -- num | from | to | keyframe
  let REkeyframesGroups =
    /(?:(?<num>[^{]{1,5})%|(?<from>from)|(?<to>to)) (?<keyframe>\{[^}]*?\})/g;

  //簡單 trim 一下 方便 匹配 字段
  let trimKeyframes = '';
  let tietu = '';
  for (var i = 0; i < styleEl.sheet.cssRules.length; i++) {
    tietu += styleEl.sheet.cssRules[i].cssText + '\n';

    if (toStringTypeCheck(styleEl.sheet.cssRules[i], 'CSSKeyframesRule')) {
      trimKeyframes = styleEl.sheet.cssRules[i].cssText;
      if (styleEl.sheet.cssRules[i].cssRules.length == 2) {
        trimKeyframes = trimKeyframes.replace('0%', 'from');
        trimKeyframes = trimKeyframes.replace('100%', 'to');
      }
    }
  }
  tietu.slice(-1, 1);
  console.log(tietu);
  styleEl.innerHTML = tietu;

  //記錄原始數據的 對象 --data 調取 索引對象key
  let loopArr = {
    data: [],
  };

  //每次 循環 的匹配值
  let regResult;

  //反轉 loopArr
  let reLoopArr = {
    data: [],
  };

  //REloop 補齊字段
  let joinstr = '';

  do {
    //獲取 匹配字段
    regResult = REkeyframesGroups.exec(trimKeyframes);
    console.log(regResult);

    if (regResult != null) {
      //提取 groups
      let reGroups = regResult.groups;

      switch (true) {
        //提取 from 信息
        case reGroups['from'] != undefined:
          // console.log("from");
          //放入 from key
          loopArr['data'].push('from');
          loopArr['from'] = reGroups.keyframe;

          break;

        //提取 to 信息
        case reGroups['to'] != undefined:
          // console.log("to");
          //放入 to key
          loopArr['data'].push('to');
          loopArr['to'] = reGroups.keyframe;
          break;

        //提取 name 信息
        case reGroups['num'] != undefined:
          // console.log("num", reGroups["num"]);
          //放入 num key
          loopArr['data'].push(reGroups.num);
          loopArr[reGroups.num] = reGroups.keyframe;
          break;
      }
    }
  } while (regResult != null);

  console.log(loopArr);

  function reKeyframe() {
    let reKeyframeBody = /@keyframes [^{]*? \{(?<changeField>[^]*)\}/;
    for (var i = 0; i < loopArr['data'].length; i++) {
      if (loopArr['data'][i] == 'from') {
        reLoopArr['data'].push('to');
        reLoopArr['to'] = loopArr[loopArr['data'][i]];
      } else if (loopArr['data'][i] == 'to') {
        reLoopArr['data'].push('from');
        reLoopArr['from'] = loopArr[loopArr['data'][i]];
      } else if (Number(loopArr['data'][i]) <= 100) {
        let reNumber = 100 - Number(loopArr['data'][i]);
        let keyaframe =
          (reNumber | 0) === reNumber ? reNumber : reNumber.toFixed(2);
        reLoopArr['data'].push(keyaframe);
        reLoopArr[keyaframe] = loopArr[loopArr['data'][i]];
      }
    }

    //補齊 字段
    if (reLoopArr['from'] != undefined) {
      joinstr += `\n\tfrom ${reLoopArr['from']}\n\tto ${reLoopArr['to']}`;
    } else {
      //重排序 默認 遞增排序
      reLoopArr['data'].sort((a, b) => a - b);
      console.log(reLoopArr['data']);

      for (var i = 0; i < reLoopArr['data'].length; i++) {
        //添加 補齊 字段
        joinstr += `\n\t${reLoopArr['data'][i]}% ${
          reLoopArr[reLoopArr['data'][i]]
        }`;
      }
      joinstr += '\n';
    }

    console.log(joinstr);

    let rekeyBody = reKeyframeBody.exec(trimKeyframes);
    console.log(rekeyBody);

    if (rekeyBody != null) {
      let rekeyBodyGs = rekeyBody.groups;
      console.log(rekeyBodyGs['changeField']);
      console.log(trimKeyframes);
      let rekeyframed = trimKeyframes.replace(
        rekeyBodyGs['changeField'],
        joinstr
      );
      //綁定 style 到 標簽
      // (不是自動綁定 可以進行數據的監聽) :(
      console.log(rekeyframed);
      styleEl.innerHTML = styleEl.innerHTML.replace(trimKeyframes, rekeyframed);
      return rekeyframed;
    }
  }

  return reKeyframe();
}

// let asc = rebackKeyframes(`@keyframes iarrH {
// 	0% {
// 	}
// 	83.34% {
// 		top: 1.8rem;
// 	}
// 	100% {
// 		top: 1.7rem;
// 	}
// }`)

/**
 * @param {Object} a
 * @param {String} type
 */
//tostring 类型检测 a 数据源 type 数据类型 （不分大小写）
function toStringTypeCheck(a, type) {
  if (type == undefined) {
    return false;
  } else if (type.toLowerCase() == 'any') {
    return true;
  }
  // console.log(toString.call(a).slice(8, -1))
  return toString.call(a).slice(8, -1).toLowerCase() == type.toLowerCase();
}
